package com.example.musicplayer.musicClass;

import android.graphics.Bitmap;

import com.example.musicplayer.musicTools.LocalMusic;
import com.example.musicplayer.musicTools.MusicFormat;
import com.example.musicplayer.musicTools.UserTableManager;
import com.example.musicplayer.musicTools.MusicSortType;
import com.example.musicplayer.user.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//存放播放器的音乐数据
public class MusicInfo {
    //存放本地查询到的音乐
    private static List<MusicInfo> sLocalMusic = new ArrayList<MusicInfo>();
    //存放本地创建的歌单
    private static List<MusicMenu> sMusicMenus = new ArrayList<MusicMenu>();
    private static Map<Integer, Integer> sFavorites = new HashMap<Integer, Integer>();
    private static Map<Integer, Integer> sListenCounts = new HashMap<Integer, Integer>();
    private int mId;
    private int mAlbumId;
    private int mSize;
    private String mTitle;
    private String mAlbum;
    private String mArtist;
    private String mPath;
    //存放歌词文件的路径
    private String mLyricPath;
    //音乐格式
    private MusicFormat mMusicFormat;

    public MusicInfo(int id, int albumId, int size, String title, String album, String artist,
                     String path, MusicFormat musicFormat) {
        mId = id;
        mAlbumId = albumId;
        mSize = size;
        mTitle = title == null ? "" : title;
        mAlbum = album == null ? "" : album;
        mArtist = artist == null ? "" : artist;
        mPath = path == null ? "" : path;
        mMusicFormat = musicFormat;
        String regex = mMusicFormat.getMusicFormatSuffix();
        if (regex != null && path != null) {
            mLyricPath = path.replaceAll(regex, ".lrc");
        }
        if (mLyricPath == null) {
            mLyricPath = "";
        }
    }

    //查询并初始化本地音乐信息
    public static void initMusicInfo() {
        //从本地查询所有music文件
        sLocalMusic = LocalMusic.getLocalMusic();
        //init table music detail
        LocalMusic.checkMusicDetail();
    }

    //init user's music info
    public static void initUserMusicInfo() {
        if (User.getInstance() != null) {
            UserTableManager.initTableManager();
            //init music menu info
            sMusicMenus = LocalMusic.getLocalMusicMenu();
            UserTableManager.updateMusicContentProvider();
            //update music sort info
            for (int i = 0; i < sMusicMenus.size(); i++) {
                sMusicMenus.get(i).updateMusicSortType();
            }
            //check the music detail user table
            LocalMusic.checkMusicDetailUser();
            //get music menu detail info
            getMusicMenuDetailInfo();
            //get music info for current user
            initMusicDetailForUser();
        }
    }

    public static boolean checkAndUpdateMusicMenu(MusicMenu musicMenu) {
        if (musicMenu != null && LocalMusic.getIfNeedUpdateMusicMenuDetail(musicMenu.getName())) {
            LocalMusic.updateIfNeedUpdateMusicMenuDetail(musicMenu.getName(), false);
            List<Integer> deleteMusic = new ArrayList<Integer>();
            List<Integer> musicList = musicMenu.getMusicList(false);
            for (int i = 0; i < musicList.size(); i++) {
                if (!has(musicList.get(i))) {
                    deleteMusic.add(musicList.get(i));
                }
            }
            deleteMusicMenuInfoById(musicMenu, deleteMusic);
            return true;
        }
        return false;
    }

    private static void initMusicDetailForUser() {
        sFavorites = LocalMusic.getMusicDetailFavorite();
        sListenCounts = LocalMusic.getMusicDetailListenCounts();
    }

    //获取本地音乐信息
    public static List<MusicInfo> getLocalMusic() {
        List<MusicInfo> temp = new ArrayList<MusicInfo>();
        for (int i = 0; i < sLocalMusic.size(); i++) {
            temp.add(sLocalMusic.get(i));
        }
        return temp;
    }

    public static List<MusicInfo> getFavoriteMusic() {
        List<MusicInfo> list = new ArrayList<>();
        for (int i = 0; i < sLocalMusic.size(); i++) {
            if (sLocalMusic.get(i).getFavorite() == 1) {
                list.add(sLocalMusic.get(i));
            }
        }
        return list;
    }

    //获取自建的歌单
    public static List<MusicMenu> getMusicMenus() {
        return sMusicMenus;
    }

    //根据歌曲id返回音乐信息对象，没有则返回null
    public static MusicInfo getMusicInfoById(int id) {
        for (int i = 0; i < sLocalMusic.size(); i++) {
            if (sLocalMusic.get(i).getId() == id) {
                return sLocalMusic.get(i);
            }
        }
        return null;
    }

    //根据歌曲id，改变歌曲favorite信息
    public static void changeMusicFavorite(int id) {
        changeMusicFavorite(getMusicInfoById(id));
    }

    //根据MusicInfo对象，改变favorite信息
    public static void changeMusicFavorite(MusicInfo musicInfo) {
        if (has(musicInfo)) {
            int favorite = 1 - musicInfo.getFavorite();
            musicInfo.setFavorite(favorite);
            LocalMusic.updateMusicFavorite(musicInfo);
        }
    }

    //歌曲加到我喜欢列表
    public static void changeToFavorite(MusicInfo musicInfo) {
        if (musicInfo != null && musicInfo.getFavorite() != 1) {
            changeMusicFavorite(musicInfo);
        }
    }

    //判断是否包含某个对象
    public static boolean has(MusicInfo musicInfo) {
        if (musicInfo != null) {
            return has(musicInfo.getId());
        }
        return false;
    }

    //判断是否有此名字的歌单
    public static boolean hasMusicMenu(String musicMenuName) {
        return getMusicMenuByName(musicMenuName) != null;
    }

    //通过歌单名获取歌单对象
    public static MusicMenu getMusicMenuByName(String musicMenuName) {
        if (musicMenuName == null || musicMenuName.equals(""))
            return null;
        for (int i = 0; i < sMusicMenus.size(); i++)
            if (musicMenuName.equals(sMusicMenus.get(i).getName()))
                return sMusicMenus.get(i);
        return null;
    }

    //判断是否包含某个id
    public static boolean has(int musicId) {
        for (int i = 0; i < sLocalMusic.size(); i++) {
            if (sLocalMusic.get(i).getId() == musicId) {
                return true;
            }
        }
        return false;
    }

    //新建歌单
    public static MusicMenu createMusicMenu(String musicMenuName) {
        if (User.getInstance() != null && UserTableManager.createMusicMenuTable(musicMenuName)) {
            MusicMenu musicMenu = new MusicMenu(musicMenuName, 0);
            //其它歌单的顺序编号增加
            for (int i = 0; i < sMusicMenus.size(); i++) {
                MusicMenu temp = sMusicMenus.get(i);
                temp.setOrder(temp.getOrder() + 1);
            }
            sMusicMenus.add(musicMenu);
            //向歌单信息表插入新建表的信息
            LocalMusic.insertMusicMenuManage(musicMenuName);
            //处理歌单顺序编号变化的事件
            changeMusicMenuOrder();
            return musicMenu;
        }
        return null;
    }

    //delete some music menu
    public static void deleteMusicMenu(List<MusicMenu> musicMenus) {
        if (User.getInstance() != null && musicMenus != null && musicMenus.size() > 0) {
            for (int i = 0; i < musicMenus.size(); i++) {
                deleteMusicMenu(musicMenus.get(i));
            }
            changeMusicMenuOrder();
        }
    }

    //delete one music menu
    private static void deleteMusicMenu(MusicMenu musicMenu) {
        String musicMenuName = musicMenu.getName();
        if (UserTableManager.deleteMusicMenuTable(musicMenuName)) {
            int order = musicMenu.getOrder();
            sMusicMenus.remove(musicMenu);
            //从歌单信息表中删除歌单信息
            LocalMusic.deleteMusicMenuManage(musicMenuName);
            //处理歌单顺序编号的变化
            for (int i = 0; i < sMusicMenus.size(); i++) {
                MusicMenu temp = sMusicMenus.get(i);
                if (temp.getOrder() > order) {
                    temp.setOrder(temp.getOrder() - 1);
                }
            }
        }
    }

    //部分歌单的排列顺序改变后调用，更新数据表
    public static void changeMusicMenuOrder() {
        if (sMusicMenus != null) {
            LocalMusic.updateMusicMenuOrder(sMusicMenus);
        }
    }

    //更新指定歌单里的歌曲的顺序
    public static void changeMusicMenuMusicOrder(MusicMenu musicMenu) {
        if (musicMenu != null) {
            String tableName = UserTableManager.getTableNameByMenuName(musicMenu.getName());
            if (tableName != null) {
                LocalMusic.updateMusicMenuMusicOrder(tableName, musicMenu.getMusicList(false)
                        , musicMenu.getMusicOrder());
            }
        }
    }

    //修改指定歌单名字
    public static boolean modifyMusicMenuName(String oldName, String newName) {
        if (oldName != null && newName != null && !oldName.equals(newName)) {
            if (UserTableManager.updateMusicMenuName(oldName, newName)) {
                LocalMusic.updateMusicMenuName(oldName, newName);
                return true;
            }
            return false;
        }
        return false;
    }

    //修改指定歌单的简介
    public static void modifyMusicMenuIntroduction(String musicMenuName, String introduction) {
        if (hasMusicMenu(musicMenuName)) {
            LocalMusic.updateMusicMenuIntroduction(musicMenuName, introduction);
        }
    }

    //修改指定歌单的歌曲排序类型
    public static void modifyMusicSortType(String musicMenuName, MusicSortType musicSortType) {
        if (hasMusicMenu(musicMenuName)) {
            LocalMusic.updateMusicMenuMusicSortType(musicMenuName, musicSortType.toString());
        }
    }

    //更新歌单点播次数
    public static void modifyMusicMenuListenCounts(String musicMenuName, int listenCounts) {
        if (hasMusicMenu(musicMenuName)) {
            LocalMusic.updateMusicMenuListenCounts(musicMenuName, listenCounts);
        }
    }

    //更新给定歌单的封面图
    public static void modifyMusicMenuBitmap(String musicMenuName, int bitmap) {
        if (hasMusicMenu(musicMenuName)) {
            LocalMusic.updateMusicMenuBitmap(musicMenuName, bitmap);
        }
    }

    //从数据库查询每个歌单的信息
    private static void getMusicMenuDetailInfo() {
        List<Integer> musicId;
        List<Integer> musicOrder;
        for (int i = 0; i < sMusicMenus.size(); i++) {
            musicId = new ArrayList<Integer>();
            musicOrder = new ArrayList<Integer>();
            String tableName = UserTableManager.getTableNameByMenuName(sMusicMenus.get(i).getName());
            if (tableName != null) {
                musicId = LocalMusic.getMusicMenuDetailId(tableName);
                musicOrder = LocalMusic.getMusicMenuDetailOrder(tableName);
            }
            sMusicMenus.get(i).setMusicList(musicId);
            sMusicMenus.get(i).setMusicOrder(musicOrder);
        }
    }

    //在歌单中插入一些音乐
    public static void insertMusicMenuInfoById(MusicMenu musicMenu, List<Integer> musicId) {
        if (User.getInstance() != null && musicMenu != null && musicId != null) {
            String tableName = UserTableManager.getTableNameByMenuName(musicMenu.getName());
            if (tableName != null) {
                for (int i = 0; i < musicId.size(); i++) {
                    if (!has(musicId.get(i)) || musicMenu.has(musicId.get(i))) {
                        musicId.remove(i);
                        i--;
                    }
                }
                //判断歌曲数量
                if (musicId.size() > 0) {
                    List<Integer> musicOrder = new ArrayList<Integer>();
                    int firstIndex = musicMenu.getCounts();
                    for (int i = 0; i < musicId.size(); i++) {
                        musicOrder.add(firstIndex++);
                    }
                    //更新数据库和内存数据
                    LocalMusic.insertMusicMenuDetail(tableName, musicId, musicOrder);
                    musicMenu.insertMusic(musicId, musicOrder);
                }
            }
        }
    }

    //向歌单中插入歌曲
    public static void insertMusicMenuInfo(MusicMenu musicMenu, List<MusicInfo> musicInfo) {
        if (User.getInstance() != null && musicInfo != null) {
            List<Integer> musicId = new ArrayList<Integer>();
            for (int i = 0; i < musicInfo.size(); i++) {
                MusicInfo temp = musicInfo.get(i);
                if (temp != null)
                    musicId.add(temp.getId());
            }
            insertMusicMenuInfoById(musicMenu, musicId);
        }
    }

    //从歌单中删除一些音乐
    public static void deleteMusicMenuInfoById(MusicMenu musicMenu, List<Integer> musicId) {
        if (musicMenu != null && musicId != null) {
            String tableName = UserTableManager.getTableNameByMenuName(musicMenu.getName());
            if (tableName != null) {
                for (int i = 0; i < musicId.size(); i++) {
                    if (!musicMenu.has(musicId.get(i))) {
                        musicId.remove(i);
                        i--;
                    }
                }
                //判断是否需要删除
                if (musicId.size() > 0) {
                    LocalMusic.deleteMusicMenuDetail(tableName, musicId);
                    musicMenu.deleteMusic(musicId);
                    //更新歌曲顺序的数据库信息
                    changeMusicMenuMusicOrder(musicMenu);
                }
            }
        }
    }

    //从歌单中删除歌曲
    public static void deleteMusicMenuInfo(MusicMenu musicMenu, List<MusicInfo> musicInfo) {
        if (musicInfo != null) {
            List<Integer> musicId = new ArrayList<Integer>();
            for (int i = 0; i < musicInfo.size(); i++) {
                MusicInfo temp = musicInfo.get(i);
                if (temp != null) {
                    musicId.add(temp.getId());
                }
            }
            deleteMusicMenuInfoById(musicMenu, musicId);
        }
    }

    //喜爱的音乐数量
    public static int getFavoriteMusicCounts() {
        if (sLocalMusic == null) {
            return 0;
        }
        int result = 0;
        for (int i = 0; i < sLocalMusic.size(); i++) {
            if (sLocalMusic.get(i).getFavorite() == 1) {
                result++;
            }
        }
        return result;
    }

    //本地音乐数量
    public static int getLocalMusicCounts() {
        if (sLocalMusic == null)
            return 0;
        return sLocalMusic.size();
    }

    //自建歌单的数量
    public static int getMusicMenuCounts() {
        if (sMusicMenus == null)
            return 0;
        return sMusicMenus.size();
    }

    //查询歌单的简介信息
    public static String getMusicMenuIntroduction(String musicMenuName) {
        if (hasMusicMenu(musicMenuName)) {
            return LocalMusic.getMusicMenuIntroduction(musicMenuName);
        }
        return null;
    }

    //获取歌曲排序类型
    public static MusicSortType getMusicSortType(String musicMenuName) {
        MusicSortType musicSortType = null;
        if (hasMusicMenu(musicMenuName)) {
            musicSortType = MusicMenu.getMusicSortType(LocalMusic.getMusicSortType(musicMenuName));
        }
        return musicSortType == null ? MusicSortType.SORT_DEFAULT : musicSortType;
    }

    public synchronized void setFavorite(int favorite) {
        if (sFavorites.containsKey(mId)) {
            if (favorite == 1) {
                sFavorites.put(mId, favorite);
            } else {
                sFavorites.put(mId, 0);
            }
        }
    }

    private synchronized void setListenCounts(int listenCounts) {
        if (listenCounts >= 0) {
            sListenCounts.put(mId, listenCounts);
        }
        LocalMusic.updateMusicListenCounts(mId, listenCounts);
    }

    //增加播放次数
    public synchronized void addListenCounts() {
        if (sListenCounts.containsKey(mId)) {
            setListenCounts(sListenCounts.get(mId) + 1);
        }
    }

    public synchronized int getFavorite() {
        if (sFavorites.containsKey(mId)) {
            return sFavorites.get(mId);
        }
        return 0;
    }

    public synchronized int getListenCounts() {
        if (sListenCounts.containsKey(mId)) {
            return sListenCounts.get(mId);
        }
        return 0;
    }

    public int getId() {
        return mId;
    }

    public int getSize() {
        return mSize;
    }

    public String getTitle() {
        return mTitle;
    }

    public String getAlbum() {
        return mAlbum;
    }

    public String getArtist() {
        return mArtist;
    }

    public String getPath() {
        return mPath;
    }

    public Bitmap getBitmap() {
        return LocalMusic.getAlbumBitmapOrDefault(this);
    }

    public String getLyricPath() {
        return mLyricPath;
    }

    public void setLyricPath(String lyricPath) {
        mLyricPath = lyricPath;
    }

    public int getAlbumId() {
        return mAlbumId;
    }

    public MusicFormat getMusicFormat() {
        return mMusicFormat;
    }
}